<?php

namespace App\Services;

use App\Models\Cart;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\UserAddress;
use App\Services\PriceCalculationService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 结算服务
 * 
 * 负责处理订单结算相关的业务逻辑，包括：
 * - 购物车结算
 * - 立即购买结算
 * - 订单创建
 * - 库存管理
 * 
 * @package App\Services
 */
class CheckoutService
{
    protected $priceCalculationService;

    public function __construct(PriceCalculationService $priceCalculationService)
    {
        $this->priceCalculationService = $priceCalculationService;
    }

    /**
     * 从购物车创建订单
     */
    public function createOrderFromCart(array $data, int $userId): Order
    {
        return DB::transaction(function () use ($data, $userId) {
            // 获取购物车
            $cart = Cart::where('user_id', $userId)->firstOrFail();
            
            // 验证购物车商品
            $this->validateCartItems($cart);
            
            // 准备购物车商品数据
            $cartItems = $cart->selectedItems->map(function ($item) {
                return [
                    'product_id' => $item->product_id,
                    'variant_id' => $item->variant_id,
                    'quantity' => $item->quantity,
                ];
            })->toArray();
            
            // 计算价格
            $priceResult = $this->priceCalculationService->calculateCartPrice($cartItems, $data['user_coupon_id'] ?? null);
            
            if (!$priceResult['success']) {
                throw new \Exception($priceResult['message']);
            }
            
            // 创建订单
            $order = $this->createOrder($data, $userId, $priceResult['data']);
            
            // 创建订单项
            $this->createOrderItemsFromCart($order, $cart);
            
            // 清空购物车
            $cart->items()->delete();
            $cart->update(['selected_items' => []]);
            
            Log::info('订单创建成功', [
                'order_id' => $order->id,
                'order_number' => $order->order_number,
                'user_id' => $userId,
                'source' => 'cart'
            ]);
            
            return $order;
        });
    }

    /**
     * 立即购买创建订单
     */
    public function createOrderFromBuyNow(array $data, int $userId): Order
    {
        return DB::transaction(function () use ($data, $userId) {
            // 从 session 获取立即购买数据
            $buyNowItem = session('buy_now_item');
            if (!$buyNowItem) {
                throw new \Exception('立即购买数据不存在');
            }
            
            // 验证商品
            $product = $this->validateProduct($buyNowItem['product_id'], $buyNowItem['variant_id'] ?? null);
            
            // 计算价格
            $priceResult = $this->priceCalculationService->calculateCartPrice([
                [
                    'product_id' => $buyNowItem['product_id'],
                    'variant_id' => $buyNowItem['variant_id'] ?? null,
                    'quantity' => $buyNowItem['quantity']
                ]
            ], $data['user_coupon_id'] ?? null);
            
            if (!$priceResult['success']) {
                throw new \Exception($priceResult['message']);
            }
            
            // 创建订单
            $order = $this->createOrder($data, $userId, $priceResult['data']);
            
            // 创建订单项
            $this->createOrderItemFromBuyNow($order, $product, $buyNowItem, $priceResult['data']);
            
            Log::info('立即购买订单创建成功', [
                'order_id' => $order->id,
                'order_number' => $order->order_number,
                'user_id' => $userId,
                'source' => 'buy_now'
            ]);
            
            return $order;
        });
    }

    /**
     * 创建订单
     */
    protected function createOrder(array $data, int $userId, array $priceData): Order
    {
        // 验证地址
        $address = UserAddress::where('id', $data['address_id'])
            ->where('user_id', $userId)
            ->firstOrFail();

        // 生成订单号
        $orderNumber = $this->generateOrderNumber();

        // 创建订单
        return Order::create([
            'order_number' => $orderNumber,
            'user_id' => $userId,
            'status' => Order::STATUS_PENDING,
            'payment_status' => Order::PAYMENT_PENDING,
            'payment_method' => $data['payment_method'] ?? Order::PAYMENT_METHOD_ALIPAY,
            'subtotal_amount' => $priceData['subtotal'],
            'shipping_fee' => $priceData['shipping_fee'],
            'discount_amount' => $priceData['discount_amount'],
            'tax_amount' => $priceData['tax_amount'],
            'total_amount' => $priceData['total_amount'],
            'user_coupon_id' => $data['user_coupon_id'] ?? null,
            'receiver_name' => $address->name,
            'receiver_phone' => $address->phone,
            'shipping_province' => $address->province,
            'shipping_city' => $address->city,
            'shipping_district' => $address->district,
            'receiver_address' => $address->address,
            'shipping_zip' => $address->zip,
            'notes' => $data['notes'] ?? null,
        ]);
    }

    /**
     * 从购物车创建订单项
     */
    protected function createOrderItemsFromCart(Order $order, Cart $cart): void
    {
        foreach ($cart->selectedItems as $cartItem) {
            $product = Product::findOrFail($cartItem->product_id);
            $variant = $cartItem->variant_id ? ProductVariant::find($cartItem->variant_id) : null;
            
            $this->createOrderItem($order, $product, $variant, $cartItem);
        }
    }

    /**
     * 立即购买创建订单项
     */
    protected function createOrderItemFromBuyNow(Order $order, Product $product, array $data, array $priceData): void
    {
        $variant = $data['variant_id'] ? ProductVariant::find($data['variant_id']) : null;
        
        $this->createOrderItem($order, $product, $variant, (object) [
            'quantity' => $data['quantity'],
            'price' => $priceData['subtotal'] / $data['quantity']
        ]);
    }

    /**
     * 创建订单项
     */
    protected function createOrderItem(Order $order, Product $product, ?ProductVariant $variant, $itemData): void
    {
        // 检查库存
        $this->checkStock($product, $variant, $itemData->quantity);
        
        // 扣减库存
        $this->updateStock($product, $variant, $itemData->quantity);
        
        // 创建订单项
        OrderItem::create([
            'order_id' => $order->id,
            'product_id' => $product->id,
            'variant_id' => $variant?->id,
            'sku' => $variant?->sku ?? $product->sku,
            'product_name' => $product->name,
            'variant_name' => $variant?->name,
            'specifications' => $this->getSpecifications($product, $variant),
            'price' => $itemData->price,
            'quantity' => $itemData->quantity,
            'total_amount' => $itemData->price * $itemData->quantity,
            'status' => 'confirmed',
        ]);
    }

    /**
     * 验证购物车商品
     */
    protected function validateCartItems(Cart $cart): void
    {
        if ($cart->selectedItems->isEmpty()) {
            throw new \Exception('购物车中没有选中的商品');
        }

        foreach ($cart->selectedItems as $item) {
            $product = Product::findOrFail($item->product_id);
            $variant = $item->variant_id ? ProductVariant::find($item->variant_id) : null;
            
            $this->checkStock($product, $variant, $item->quantity);
        }
    }

    /**
     * 验证商品
     */
    protected function validateProduct(int $productId, ?int $variantId): Product
    {
        $product = Product::findOrFail($productId);
        $variant = $variantId ? ProductVariant::find($variantId) : null;
        
        if ($variant && $variant->product_id !== $product->id) {
            throw new \Exception('商品变体不匹配');
        }
        
        return $product;
    }

    /**
     * 检查库存
     */
    protected function checkStock(Product $product, ?ProductVariant $variant, int $quantity): void
    {
        $availableStock = $variant ? $variant->stock_quantity : $product->stock_quantity;
        
        if ($availableStock < $quantity) {
            throw new \Exception("库存不足，当前库存：{$availableStock}");
        }
    }

    /**
     * 更新库存
     */
    protected function updateStock(Product $product, ?ProductVariant $variant, int $quantity): void
    {
        if ($variant) {
            $variant->decrement('stock_quantity', $quantity);
        } else {
            $product->decrement('stock_quantity', $quantity);
        }
    }

    /**
     * 获取规格信息
     */
    protected function getSpecifications(Product $product, ?ProductVariant $variant): array
    {
        if ($product->product_type === 'single') {
            return [];
        }
        
        if (!$variant) {
            return [];
        }
        
        // 确保预加载 attributeValues 和 attribute 关系
        $variant->load(['attributeValues.attribute']);
        
        // 使用 attributeValues 关系获取规格信息
        return $variant->attributeValues->map(function ($attr) {
            return [
                'name' => $attr->attribute->name,
                'value' => $attr->value
            ];
        })->toArray();
    }

    /**
     * 准备订单项数据
     */
    protected function prepareOrderItems(array $data): array
    {
        // 这里可以根据实际需求处理订单项数据
        return $data['items'] ?? [];
    }

    /**
     * 生成订单号
     */
    protected function generateOrderNumber(): string
    {
        return date('Ymd') . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
    }
}
